<template>
  <el-dialog :v-loading="isLoading" :close-on-click-modal="false" class="assign-role" title="分配角色" :visible="showRoleDialog" @open="openDialog" @close="closeRoleDialog">
    <!-- 这里准备复选框 -->
    <el-checkbox-group v-model="roleIds">
      <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">
        {{ item.name }}
      </el-checkbox>
    </el-checkbox-group>

    <template #footer>
      <el-button type="primary" size="small" @click="submitRoleIds">确定</el-button>
      <el-button size="small" @click="closeRoleDialog">取消</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { getRoleListApi, assignRolesApi } from '@/api/role'
import { employeeInfoApi } from '@/api/user'
export default {
  props: {
    showRoleDialog: {
      type: Boolean,
      default: false
    },
    // 用户的id 用来查询当前用户的角色信息
    userId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      roleList: [],
      roleIds: [],
      isLoading: false
    }
  },
  methods: {
    // 打开弹窗调用
    async openDialog() {
      this.isLoading = true
      await this.getRoleList()
      await this.getRoleDetails()
      this.isLoading = false
    },
    // 获取角色信息
    async getRoleList() {
      const { data } = await getRoleListApi(1, 9999)
      this.roleList = data.data.rows
      console.log(this.roleList)
      this.getRoleDetails()
    },
    // 回显角色信息
    async getRoleDetails() {
      const { data } = await employeeInfoApi(this.userId)
      // console.log(data)
      this.roleIds = data.data.roleIds
    },
    // 关闭弹层
    closeRoleDialog() {
      this.$emit('update:showRoleDialog', false)
    },
    // 点击确定发送请求
    async submitRoleIds() {
      // const id = this.userId
      // const roleIds = this.roleIds
      // console.log(id)
      // console.log(roleIds)
      assignRolesApi({ id: this.userId, roleIds: this.roleIds }).then(res => {
        this.$message.success('修改成功')
      })
      //   .catch(err => {
      //     this.$message.error('更改失败')
      //     console.log(err)
      //   })

      this.closeRoleDialog()
    }
  }
}
</script>
